<?php

namespace app\service;

use app\common\BaseService;
use app\model\Order as OrderModel;
use app\model\Serial as SerialModel;
use think\facade\Db;

class OrderService extends BaseService
{
  public static function getInstance(): OrderService
  {
    return parent::getInstance();
  }

  public static function getModel(): OrderModel
  {
    return OrderModel::getInstance();
  }

  public static function getSerialModel(): SerialModel
  {
    return SerialModel::getInstance();
  }

  /*
   * 列表
   */
  public static function getOrderList($condition, $page, $pageSize = 30, $order = ['id' => 'desc']) {
    return self::getModel()->getDataDetail($condition, $page, $pageSize, $order);
  }

  /*
   * 分页
   */
  public static function getOrderPager($condition, $page, $pageSize = 30) {
    return self::getModel()->pager($condition, $page, $pageSize);
  }

  /*
   * 新增订单
   */
  public static function createOrder($data) {
    $oid = '';
    if (isset($data['oid']) && $data['oid']) {
      $oid = $data['oid'];
    } else {
      // 获取订单号
      $oid = self::getModel()->field(['max(oid)+1 as oid'])->select()->toArray();
      if (isset($oid[0])) {
        $oid = $oid[0]['oid'];
      } else {
        $oid = 0;
      }
    }
    // 获取仓库数据
    $house = HouseService::getModel()
      ->find($data['model'])
      ->toArray();
    // 新增order_t
    $insertOrder = [
      'oid' => $oid,
      'date' => $data['date'],
      'product' => $house['product'],
      'model' => $house['model'],
      'productn' => $house['productn'],
      'customer' => trim($data['customer']),
      'address' => $data['address'],
      'cname' => $data['cname'],
      'phone' => str_replace(' ', '', $data['phone']),
      'cost' => $house['nowcost'],
      'price' => $data['price'],
      'amoumt' => $data['amoumt'],
      'discount' => $data['discount'],
      'tprice' => round($data['price']*$data['amoumt']-$data['discount'], 2),
      'paid' => $data['paid'],
      'npaid' => round(($data['price']*$data['amoumt'] - $data['discount']-$data['paid']), 2),
      'unit' => $house['unit'],
      'other' => $data['other'],
      'invoice' => $data['invoice'],
      'tax' => $data['tax'],
      'send' => 0,
      'installtime' => $data['installtime'] ? $data['installtime'] : null,
      'itime' => $data['itime'] ? $data['itime'] : null,
      'new' => $data['new'],
      'sendtime' => null,
      'js' => $data['js'],
      'ispw' => $data['ispw']
    ];
    // 更新house
    if ($data['new']) {
      $updateHouse = [
        'amoumt' => $house['amoumt'] - $data['amoumt'],
        'wamoumt' => $house['wamoumt'] + $data['amoumt']
      ];
    } else {
      $updateHouse = [
        'oldamoumt' => $house['oldamoumt'] - $data['amoumt'],
        'oldwamoumt' => $house['oldwamoumt'] + $data['amoumt']
      ];
    }
    $houseId = $house['id'];
    self::getModel()->startTrans();
    try {
      if ($insertOrder) {
        $res = self::getModel()->save($insertOrder);
        if (!$res) {
          throw new \Exception('新增order失败');
        }
      }
      if ($updateHouse) {
        $res1 = HouseService::getModel()
          ->where('id', '=', $houseId)
          ->update($updateHouse);
        if (!$res1) {
          throw new \Exception('修改house失败');
        }
      }
      self::getModel()->commit();
      return ['status' => true, 'msg' => 'ok'];
    } catch (\Exception $e) {
      self::getModel()->rollback();
      return ['status' => false, 'msg' => $e->getMessage()];
    }
  }

  /*
   * 修改
   */
  public static function updateOrder($id, $data) {
    // 修改订单数据
    $orderForm = $data['orderForm'];
    // 修改详细数据
    $updateForm = $data['updateForm'];
    // 查看原数据
    $order = OrderService::getModel()->find($id)->toArray();
    // 修改order_t中id数据
    $update = [
      'price' => $updateForm['price'] ? $updateForm['price'] : 0,
      'discount' => $updateForm['discount'] ? $updateForm['discount'] : 0,
      'tprice' => round($updateForm['price']*$updateForm['amoumt']-$updateForm['discount'], 2),
      'paid' => $updateForm['paid'] ? $updateForm['paid'] : 0,
      'npaid'=> round(($updateForm['price']*$updateForm['amoumt'] - $updateForm['discount']-$updateForm['paid']), 2),
      'other' => $updateForm['other'] ? $updateForm['other'] : '',
      'date' => $orderForm['date'] ? $orderForm['date'] : null,
      'customer' => $orderForm['customer'] ? $orderForm['customer'] : '',
      'address' => $orderForm['address'] ? $orderForm['address'] : '',
      'cname' => $orderForm['cname'] ? $orderForm['cname'] : '',
      'phone' => $orderForm['phone'] ? str_replace(' ', '',$orderForm['phone']) : '',
      'js' => $orderForm['js'] ? $orderForm['js'] : '',
      'invoice' => $orderForm['invoice'] ? $orderForm['invoice'] : '0',
      'tax' => $orderForm['tax'] ? $orderForm['tax'] : '0',
      'ispw' => $orderForm['ispw'] ? $orderForm['ispw'] : '0',
      'yf' => $orderForm['yf'] ? $orderForm['yf'] : '0',
      'azf' => $orderForm['azf'] ? $orderForm['azf'] : '0',
      'installtime' => $orderForm['installtime'] ? $orderForm['installtime'] : null,
      'itime' => $orderForm['itime'] ? $orderForm['itime'] : null
    ];
    // 修改order_t中date-oid-customer数据
    $updateOrder = [
      'date' => $orderForm['date'] ? $orderForm['date'] : null,
      'customer' => $orderForm['customer'] ? $orderForm['customer'] : '',
      'address' => $orderForm['address'] ? $orderForm['address'] : '',
      'cname' => $orderForm['cname'] ? $orderForm['cname'] : '',
      'phone' => $orderForm['phone'] ? str_replace(' ', '',$orderForm['phone']) : '',
      'js' => $orderForm['js'] ? $orderForm['js'] : '',
      'invoice' => $orderForm['invoice'] ? $orderForm['invoice'] : '0',
      'tax' => $orderForm['tax'] ? $orderForm['tax'] : '0',
      'ispw' => $orderForm['ispw'] ? $orderForm['ispw'] : '0',
      'yf' => $orderForm['yf'] ? $orderForm['yf'] : '0',
      'azf' => $orderForm['azf'] ? $orderForm['azf'] : '0',
      'installtime' => $orderForm['installtime'] ? $orderForm['installtime'] : null,
      'itime' => $orderForm['itime'] ? $orderForm['itime'] : null,
    ];
    $orders = self::getModel()
      ->where('oid', '=', $order['oid'])
      ->where('date', '=', $order['date'])
      ->where('customer', '=', $order['customer'])
      ->select()
      ->toArray();
    $orderIds = [];
    foreach ($orders as $orderId){
      if ($orderId['id'] != $id) {
        $orderIds[] = $orderId['id'];
      }
    }
    self::getModel()->startTrans();
    try {
      // 修改ID对应数据
      if ($update) {
        self::getModel()->where('id', $id)->update($update);
      }
      // 修改date-oid-customer对于数据
      if ($updateOrder && $orderIds) {
        foreach ($orderIds as $v) {
          self::getModel()->where('id', $v)->update($updateOrder);
        }
      }
      self::getModel()->commit();
      return ['status' => true, 'msg' => 'ok'];
    } catch (\Exception $e) {
      self::getModel()->rollback();
      return ['status' => false, 'msg' => $e->getMessage()];
    }

  }

  /*
   * 删除
   */
  public static function deleteOrder($id) {
    // 获取订单数据
    $order = self::getModel()->find($id)->toArray();
    // 更新house的数据
    $updateHouse = [];
    // 是否展厅数据
    if (!$order['resource']) {
      // 获取仓库数据
      $house = HouseService::getModel()
        ->where('model', '=', $order['model'])
        ->select()
        ->toArray();
      $house = isset($house[0]) ? $house[0] : [];

      // 已发货
      if($order['send']=='1'){
        return ['status' => false, 'msg' => '请先取消订单发货'];
      }
      // 旧品
      if($order['new']){
        $updateHouse = [
          'amoumt' => $house['amoumt'] + $order['amoumt'],
          'wamoumt' => $house['wamoumt'] - $order['amoumt']
        ];
        //新品
      } else{
        $updateHouse = [
          'oldamoumt' => $house['oldamoumt'] + $order['amoumt'],
          'oldwamoumt' => $house['oldwamoumt'] - $order['amoumt']
        ];
      }
    }

    self::getModel()->startTrans();
    try {
      if ($updateHouse) {
        $res = HouseService::getModel()
          ->where('id', '=', $house['id'])
          ->update($updateHouse);
        if (!$res) {
          throw new \Exception('更新house失败');
        }
      }
      if ($order['resource']) {
        $res1 = ShowService::getModel()
          ->where('id', $order['show_id'])
          ->update(['states' => 1]);
        if (!$res1) {
          throw new \Exception('更新show_t失败');
        }
      }
      $res2 = self::getModel()
        ->where('id', '=', $id)
        ->delete();
      if (!$res2) {
        throw new \Exception('删除order失败');
      }
      self::getModel()->commit();
      return ['status' => true, 'msg' => 'ok'];
    } catch (\Exception $e) {
      self::getModel()->rollback();
      return ['status' => false, 'msg' => $e->getMessage()];
    }

  }

  /*
   * 发货
   */
  public static function confirmOrder($oid) {
    $nowDate = date('Y-m-d H:i:s');
    // 该订单所有数据
    $orderList = self::getModel()
      ->where('oid', '=', $oid)
      ->select()
      ->toArray();
    // 修改house
    $updateHouse = [];
    // 修改order
    $updateOrder = [];
    // 获取仓库信息
    $res = HouseService::getModel()
      ->select()
      ->toArray();
    $houseList = [];
    foreach ($res as $v) {
      $str = $v['productn'].'-'.$v['model'];
      $houseList[$str] = $v;
    }
    // 获取子数据
    foreach ($orderList as $value) {
      // 仓库当前数据
      $str = $value['productn'].'-'.$value['model'];
      $house = $houseList[$str];
      // 是否有相同数据
      if (isset($updateHouse[$house['id']])) {
        // 上级总数量
        if ($value['new']) {  // 新品
          $updateHouse[$house['id']]['wamoumt'] = isset($updateHouse[$house['id']]['wamoumt']) ? $updateHouse[$house['id']]['wamoumt'] : $house['wamoumt'];
          if ($updateHouse[$house['id']]['wamoumt'] < $value['amoumt']) {
            return ['status' => false, 'msg' => $str.' 库存不足'];
          }
          $updateHouse[$house['id']]['wamoumt'] = $updateHouse[$house['id']]['wamoumt'] - $value['amoumt'];
        } else {  // 旧品
          $updateHouse[$house['id']]['oldwamoumt'] = isset($updateHouse[$house['id']]['oldwamoumt']) ? $updateHouse[$house['id']]['oldwamoumt'] : $house['oldwamoumt'];
          if ($updateHouse[$house['id']]['oldwamoumt'] < $value['amoumt']) {
            return ['status' => false, 'msg' => $str.' 库存不足'];
          }
          $updateHouse[$house['id']]['oldwamoumt'] = $updateHouse[$house['id']]['oldwamoumt'] - $value['amoumt'];
        }
      } else {
        $updateHouse[$house['id']]['id'] = $house['id'];
        if ($value['new']) {  // 新品
          if ($house['wamoumt'] < $value['amoumt']) {
            return ['status' => false, 'msg' => $str.' 库存不足'];
          }
          $updateHouse[$house['id']]['wamoumt'] = $house['wamoumt'] - $value['amoumt'];
        } else {  // 旧品
          if ($house['oldwamoumt'] < $value['amoumt']) {
            return ['status' => false, 'msg' => $str.' 库存不足'];
          }
          $updateHouse[$house['id']]['oldwamoumt'] = $house['oldwamoumt'] - $value['amoumt'];
        }
      }
      $updateOrder[] = [
        'id' => $value['id'],
        'cost' => $house['nowcost'],
        'send' => 1,
        'sendtime' => $nowDate
      ];
    }
    // 获取修改的orderIds
    self::getModel()->startTrans();
    try {
      // 修改house
      if ($updateHouse) {
        foreach ($updateHouse as $key => $value) {
          $res1 = HouseService::getModel()
            ->where('id', '=', $key)
            ->update($value);
          if ($res1 === false) {
            throw new \Exception('更新house失败');
          }
        }
      }
      // 修改order
      if ($updateOrder) {
        $res2 = self::getModel()->saveAll($updateOrder);
        if ($res2 === false) {
          throw new \Exception('更新order失败');
        }
      }

      self::getModel()->commit();
      return ['status' => true, 'msg' => 'ok'];
    } catch (\Exception $e) {
      self::getModel()->rollback();
      return ['status' => false, 'msg' => $e->getMessage()];
    }
  }

  /*
   * 撤销发货
   */
  public static function cancelOrder($oid) {
    // 该订单所有数据
    $orderList = self::getModel()
      ->where('oid', '=', $oid)
      ->select()
      ->toArray();
    $orderIds = array_column($orderList, 'id');
    // 修改house
    $updateHouse = [];
    // 获取仓库信息
    $res = HouseService::getModel()
      ->select()
      ->toArray();
    $houseList = [];
    foreach ($res as $v) {
      $str = $v['productn'].'-'.$v['model'];
      $houseList[$str] = $v;
    }

    foreach ($orderList as $value) {
      // 仓库当前数据
      $str = $value['productn'].'-'.$value['model'];
      $house = $houseList[$str];
      // 修改前数量
      $count = $house['amoumt'] + $house['wamoumt'] + $house['oldamoumt'] + $house['oldwamoumt'];
      // 修改前总价
      $total = $count * $house['nowcost'];
      // 是否有相同数据
      if (isset($updateHouse[$house['id']])) {
        // 上级总数量
        $all = $house['amoumt'] + (isset($updateHouse[$house['id']]['wamoumt']) ? $updateHouse[$house['id']]['wamoumt'] : $house['wamoumt']) + $house['oldamoumt'] + (isset($updateHouse[$house['id']]['oldwamoumt']) ? $updateHouse[$house['id']]['oldwamoumt'] : $house['oldwamoumt']);
        $updateHouse[$house['id']]['nowcost'] = round(($all * $updateHouse[$house['id']]['nowcost'] + $value['amoumt'] * $value['cost']) / ( $all + $value['amoumt']), 2);
        if ($value['new']) {  // 新品
          $updateHouse[$house['id']]['wamoumt'] = (isset($updateHouse[$house['id']]['wamoumt']) ? $updateHouse[$house['id']]['wamoumt'] : $house['wamoumt']) + $value['amoumt'];
        } else {  // 旧品
          $updateHouse[$house['id']]['oldwamoumt'] = (isset($updateHouse[$house['id']]['oldwamoumt']) ? $updateHouse[$house['id']]['oldwamoumt'] : $house['oldwamoumt']) + $value['amoumt'];
        }
      } else {
        $updateHouse[$house['id']]['id'] = $house['id'];
        $updateHouse[$house['id']]['nowcost'] = round((($total + ($value['amoumt'] * $value['cost']))) / ($count + $value['amoumt']), 2);
        if ($value['new']) {  // 新品
          $updateHouse[$house['id']]['wamoumt'] = $house['wamoumt'] + $value['amoumt'];
        } else {  // 旧品
          $updateHouse[$house['id']]['oldwamoumt'] = $house['oldwamoumt'] + $value['amoumt'];
        }
      }
    }
    self::getModel()->startTrans();
    try {
      // 修改house
      if ($updateHouse) {
        foreach ($updateHouse as $key => $value) {
          $res = HouseService::getModel()
            ->where('id', '=', $key)
            ->update($value);
          if (!$res) {
            throw new \Exception('更新house失败');
          }
        }
      }
      // 修改order
      if ($orderIds) {
        // 修改order
        foreach ($orderIds as $orderId) {
          $res2 = self::getModel()
            ->where('id', $orderId)
            ->update([
              'send' => 0,
              'sendtime' => null
            ]);
          if (!$res2) {
            throw new \Exception('更新order失败');
          }
        }
      }
      self::getModel()->commit();
      return ['status' => true, 'msg' => 'ok'];
    } catch (\Exception $e) {
      self::getModel()->rollback();
      return ['status' => false, 'msg' => $e->getMessage()];
    }
  }

  /*
   * 获取所有数据
   */
  public static function getAllOrder($conditions, $order) {
    $result = self::getModel();
    foreach ($conditions as $item) {
      list($field, $value, $op) = $item;
      if (!$op) {
        $op = '=';
      }
      $result = $result->where($field, $op, $value);
    }
    if ($order) {
      $result = $result->order($order);
    }
    return $result->select()->toArray();
  }

  /*
   * 展厅新增订单
   */
  public static function createPurchase($data) {
    // 新增到订单的订单号
    $oid = self::getModel()->field(['max(oid)+1 as oid'])->select()->toArray();
    if (isset($oid[0])) {
      $oid = $oid[0]['oid'];
    } else {
      $oid = 0;
    }
    // 获取该展厅数据
    $show = ShowService::getModel()
      ->where('id', '=', $data['id'])
      ->find()
      ->toArray();
    // 新增order_t
    $insertOrder = [
      'oid' => $oid,
      'date' => $data['date'],
      'product' => $show['product'],
      'model' => $show['model'],
      'productn' => $show['productn'],
      'customer' => trim($data['customer']),
      'address' => $data['address'],
      'cname' => $data['cname'],
      'phone' => str_replace(' ', '', $data['phone']),
      'cost' => $show['cost'],
      'price' => $data['price'],
      'amoumt' => $data['amoumt'],
      'discount' => $data['discount'],
      'tprice' => round($data['price']*$data['amoumt']-$data['discount'], 2),
      'paid' => $data['paid'],
      'npaid' => round(($data['price']*$data['amoumt'] - $data['discount']-$data['paid']), 2),
      'unit' => $show['unit'],
      'other' => $data['other'],
      'invoice' => $data['invoice'],
      'tax' => $data['tax'],
      'send' => 1,
      'installtime' => $data['installtime'] ? $data['installtime'] : null,
      'itime' => $data['itime'] ? $data['itime'] : null,
      'new' => $data['new'],
      'sendtime' => $data['date'],
      'js' => $data['js'],
      'ispw' => 0,
      'resource' => 1,
      'show_id' => $data['id']
    ];
    self::getModel()->startTrans();
    try {
      // 新增订单数据
      if ($insertOrder) {
        $res = self::getModel()->save($insertOrder);
        if (!$res) {
          throw new \Exception('新增order失败');
        }
      }
      // 更新展厅列表状态
      $res1 = ShowService::getModel()
        ->where('id', $data['id'])
        ->update([
          'states' => 2,
          'other' => $data['other']
        ]);
      if (!$res1) {
        throw new \Exception('修改show失败');
      }
      self::getModel()->commit();
      return ['status' => true, 'msg' => 'ok'];
    } catch (\Exception $e) {
      self::getModel()->rollback();
      return ['status' => false, 'msg' => $e->getMessage()];
    }

  }

  /*
   * 还款
   */
  public static function confirmRepayOrder($id = '', $oid = '') {
    if ($id) {
      $res = self::getModel()
        ->where('id', $id)
        ->update([
          'is_repayment' => 1,
          'repaytime' => date('Y-m-d H:i:s')
        ]);
    } elseif ($oid) {
      $res = self::getModel()
        ->where('oid', '=', $oid)
        ->update([
          'is_repayment' => 1,
          'repaytime' => date('Y-m-d H:i:s')
        ]);
    }
    if ($res === false) {
      return ['status' => false, 'msg' => '更新order失败'];
    }
    return ['status' => true, 'msg' => 'ok'];
  }

  /*
   * 撤销还款
   */
  public static function cancelRepayOrder($id = '', $oid = '') {
    if ($id) {
      $res = self::getModel()
        ->where('id', $id)
        ->update([
          'is_repayment' => 0,
          'repaytime' => null
        ]);
    } elseif ($oid) {
      $res = self::getModel()
        ->where('oid', '=', $oid)
        ->update([
          'is_repayment' => 0,
          'repaytime' => null
        ]);
    }
    if ($res === false) {
      return ['status' => false, 'msg' => '更新order失败'];
    }
    return ['status' => true, 'msg' => 'ok'];

  }

  /*
   * 获取某个订单的所有序列号
   */
  public function getOrderSerial($oid) {
    $data = Db::table('serial')
      ->alias('s')
      ->field('o.*, s.serial_number')
      ->join('order_t o', 'o.id = s.order_id', 'LEFT')
      ->where('o.oid', '=', $oid)
      ->order('o.product', 'desc')
      ->order('o.productn', 'desc')
      ->order('o.id', 'desc')
      ->select()
      ->toArray();
    if ($data === false) {
      return ['status' => false, 'msg' => '获取order失败'];
    }
    return ['status' => true, 'data' => $data];
  }

  /*
   * 获取order_t关联序列号
   */
  public static function getSerialById($order_id) {
    $result = self::getSerialModel()
      ->where('order_id', '=', $order_id)
      ->select();
    if ($result) {
      return $result->toArray();
    }
    return [];
  }

  /**
   * 保存序列号
   */
  public static function updateSerialById($order_id, $data) {
    $add = [];
    $diff = [];
    foreach ($data as $value) {
      if (isset($diff[$order_id]) && in_array($value['serial_number'], $diff[$order_id])) {
        return ['status' => false, 'msg' => '订单中同一商品，序列号不能相同'];
      }
      $add[] = [
        'order_id' => $order_id,
        'serial_number' => $value['serial_number']
      ];
      $diff[$order_id][] = $value['serial_number'];
    }
    self::getSerialModel()->startTrans();
    try {
      $res1 = self::getSerialModel()
        ->where('order_id', '=', $order_id)
        ->delete();
      if ($res1 === false) {
        throw new \Exception('删除serial失败');
      }
      if ($add) {
        $res2 = self::getSerialModel()->insertAll($add);
        if ($res2 === false) {
          throw new \Exception('新增serial失败');
        }
      }
      self::getSerialModel()->commit();
      return ['status' => true, 'msg' => 'ok'];
    } catch (\Exception $e) {
      self::getSerialModel()->rollback();
      return ['status' => false, 'msg' => $e->getMessage()];
    }
  }
}